package org.openstock.impl.def.charting.ui.swing.presenter.delegate.composer;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JSplitPane;

import org.openstock.api.charting.presenter.delegate.composer.ViewComposer;
import org.openstock.impl.def.charting.ui.swing.view.DefaultStockMultiChartView;
import org.openstock.impl.def.core.ui.swing.wrapper.JComponent;
import org.openstock.impl.def.core.ui.swing.wrapper.MultiSplitLayout.Divider;
import org.openstock.impl.def.core.ui.swing.wrapper.MultiSplitLayout.Leaf;
import org.openstock.impl.def.core.ui.swing.wrapper.MultiSplitLayout.Node;
import org.openstock.impl.def.core.ui.swing.wrapper.MultiSplitLayout.Split;
import org.openstock.impl.def.core.ui.swing.wrapper.MultiSplitPane;

public class DefaultStockMultiChartViewComposer implements ViewComposer<DefaultStockMultiChartView> {

	@Override
	public void compose(DefaultStockMultiChartView view) {
		view.add(split(view.getChildren()));
	}
	
	
	
	public Component split(List<? extends JComponent> componentList){
		if(componentList == null || componentList.isEmpty()){
			return null;
		}else if(componentList.size() == 1){
			return componentList.get(0);
		}else if(componentList.size() == 2){
			return new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
					componentList.get(0),componentList.get(1));
		}
		
			int x = 1;
			int y = 1;
			int count = componentList.size();
			
			while(x*y < count){
				y++;
				if(x*y <count){
					x++;
				}else{
					break;
				}
			}
			
			Split mainSplit = new Split();
			mainSplit.setRowLayout(true);
			List<Node> splitList = new ArrayList<Node>();
			
			Divider extraSplitDivider = null;
			for(int i = 0; i < y ; i++){
				Split split = new Split();
				split.setRowLayout(false);
				List<Node> nodeList = new ArrayList<Node>();
				Divider extraLeafDivider = null;
				for(int j = 0; j < x; j++){
					Leaf leaf = new Leaf(String.valueOf(i)+j);
					nodeList.add(leaf);
					extraLeafDivider = new Divider();
					nodeList.add(extraLeafDivider);
				}
				nodeList.remove(extraLeafDivider);
				split.setChildren(nodeList);
				splitList.add(split);
				extraSplitDivider = new Divider();
				splitList.add(extraSplitDivider);
			}
			splitList.remove(extraSplitDivider);
			
			mainSplit.setChildren(splitList);
			MultiSplitPane multiSplitPane = new MultiSplitPane();
			multiSplitPane.getMultiSplitLayout().setModel(mainSplit);
			
			count = 0;
			for(int i = 0; i < y ; i++){
				for(int j = 0; j < x; j++){
					if(count >= componentList.size()){
						break;
					}
					Component component = componentList.get(count);
					multiSplitPane.add(component,String.valueOf(i)+j);
					count++;
				}
			}
			return multiSplitPane;
		}

}
